/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swa.e_store.businessLogic;

import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import swa.e_store.DTO.StockDTO;
import swa.e_store.entity.Stock;

/**
 *
 * @author Stefan
 */
public class BL_Stock {
    
    public BL_Stock(){
        
    }
    
    public StockDTO createStockTable(){
        String[] columnNames = {"Id", "ArtNbr", "Quantity", "ShopNbr"};
        
        Object[][] data;
        
        //GetArticles
        List<Stock> artList = getAllStock();
        
        
        // Fill Data.
        Iterator<Stock> it = artList.iterator();
        data = new Object[artList.size()][4];
        int i=0;
        while(it.hasNext()) {
            Stock stock = it.next();
            data[i][0]= stock.getId();
            data[i][1]= stock.getArtNbr();
            data[i][2]= stock.getQuantity();
            data[i][3]= stock.getShopNbr();
            i++;
        }
        
        // In DTO Abfüllen
        
        StockDTO stockDTO = new StockDTO();
        stockDTO.setColumnNames(columnNames);
        stockDTO.setData(data);
        
        return stockDTO;
    }
    
     /**
     *  Returns a list of all articles.
     * 
     * @return 
     */
        public List<Stock> getAllStock(){
            
        //EMFactory
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Napier_E-StorePU");
        
        //EntityManager
        EntityManager eManager = emFactory.createEntityManager();
        
        //Start Transaction
        EntityTransaction tx = eManager.getTransaction();
        tx.begin();
        
        try
        {
            List<Stock> stock = eManager.createNamedQuery("stock.findAll").getResultList();
            return stock;
        }
        catch (Exception ex)
        {
            System.out.println(ex);
            return null;
        }
        finally
        {
            eManager.close();
            emFactory.close();
        }
        
    }
}
